package base;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Map;

public class BaseServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
             String methodName = null;
            String contentType = req.getHeader("Content-Type");
            if ("application/json;charset=utf-8".equals(contentType)){
                String postJSON = getPostJSON(req);
                Map<String,Object> map = JSON.parseObject(postJSON, Map.class);
                methodName = (String) map.get("methodName");
                req.setAttribute("map",map);
            }else {
             methodName = req.getParameter("methodName");
            }
            if (methodName != null) {
                Class c = this.getClass();
                Method method = c.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
                method.invoke(this, req, resp);
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("没有此方法名！");

        }
    }

    @Override
    protected void doPost (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }


    public String getPostJSON(HttpServletRequest req){
        try {
            BufferedReader reader = req.getReader();
            StringBuffer sb = new StringBuffer();
            String line = null;
            while ( (line = reader.readLine()) != null){
                sb.append(line);
            }
            return sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

}